package com.flute.framework.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class XPathUtils {

	public static String getFirstAttributeValue(Document root, String path) {
		try {
			List<?> attList = XPath.selectNodes(root.getRootElement(), path);
			if (attList != null && attList.size() > 0) {
				Object first = attList.get(0);
				if (first != null && first instanceof Attribute) {
					return ((Attribute) attList.get(0)).getValue();
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String[] getAttributeValues(Document root, String path) {
		List<String> valueList = new ArrayList<String>();
		try {
			List<?> attList = XPath.selectNodes(root.getRootElement(), path);
			if (attList != null) {
				for (Object e : attList) {
					if (e != null && e instanceof Attribute) {
						valueList.add(((Attribute) e).getValue());
					}
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}

		return valueList.toArray(new String[valueList.size()]);
	}

	public static String getFirstNodeValue(Document root, String path) {
		try {
			List<?> list = XPath.selectNodes(root.getRootElement(), path);
			if (list != null && list.size() > 0) {
				Object first = list.get(0);
				if (first != null && first instanceof Element) {
					return ((Element) first).getValue();
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String[] getNodeValues(Document root, String path) {
		List<String> valueList = new ArrayList<String>();
		try {
			List<?> elementList = XPath
					.selectNodes(root.getRootElement(), path);
			if (elementList != null) {
				for (Object e : elementList) {
					if (e != null && e instanceof Element) {
						valueList.add(((Element) e).getValue());
					}
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		return valueList.toArray(new String[valueList.size()]);
	}

	public static boolean isAttribute(String xpath) {
		if (xpath != null) {
			int pos = xpath.trim().lastIndexOf("/");
			if (pos >= 3) {
				return xpath.substring(pos+1).startsWith("@");
			}
		}
		return false;
	}

	public static void main(String[] args) throws JDOMException, IOException {
		String fileName = "/home/xww/下载/xpath/a.xml";
		File f = new File(fileName);
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(f);
		String firstValue = getFirstNodeValue(doc, "//result/songs");
		System.out.println(firstValue);
	}
}
